//
//  NetworkTools.swift
//  HJWeiBo
//
//  Created by 黄珏 on 15/10/28.
//  Copyright © 2015年 黄珏. All rights reserved.
//

import UIKit
import AFNetworking

class NetworkTools: AFHTTPSessionManager {
    
//    错误枚举
    enum HJNetWorkError: Int {
        case emptyToken = -1
        case emptyUID = -2
        
        var description: String {
            get{
                switch self {
                case HJNetWorkError.emptyToken:
                    return "Token为空"
                case HJNetWorkError.emptyUID:
                    return "UID为空"
                }
            }
        }
        
        func error() ->NSError {
            return NSError(domain: "cn.itcast.error.network", code: rawValue, userInfo: ["errorDescription": description])
        }
    }
    
    static let shareInstance: NetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tools = NetworkTools(baseURL: baseURL)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        }()
    //MARK: - Oauth授权
    private let client_id = "352531691"
    private let app_secret = "b88c0073fe09dd1a5f613a00c3083685"
    let redirect_uri = "http://www.baidu.com/"
    let grant_type = "authorization_code"
    
    /// 授权的URL
    func oauthUrl() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    
    func loadUserInfo(finish: NetworkFinishedCallback) {
        if HJUserAccount.loadUserAccount()?.access_token == nil {
            return
        }
        if HJUserAccount.loadUserAccount()?.uid == nil {
            return
        }
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 参数
        let parameters = [
            "access_token": HJUserAccount.loadUserAccount()!.access_token!,
            "uid": HJUserAccount.loadUserAccount()!.uid!
        ]
        
        requestGET(urlString, parameters: parameters, finshed: finish)
    }
    
    // 类型别名 = typedefined
    typealias NetworkFinishedCallback = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    func loadAccessToken(code: String,finish: NetworkFinishedCallback) {
        //        准备url
        let tokenURL = "https://api.weibo.com/oauth2/access_token"
        //        准备字典
        let dic: Dictionary = [
            "client_id" : client_id,
            "client_secret" : app_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        requestPOST(tokenURL, parameters: dic, finshed: finish)
    }
    /// 判断access token是否有值,没有值返回nil,如果有值生成一个字典
    func tokenDict(finish: NetworkFinishedCallback) -> [String: AnyObject]? {
        if HJUserAccount.loadUserAccount()?.access_token == nil {
            let error = HJNetWorkError.emptyToken.error()
            finish(result: nil, error: error)
            return nil
        }
        return ["access_token": HJUserAccount.loadUserAccount()!.access_token!]
    }
    
    /// 加载本地微博数据
    func loadLocalStatus(finish: NetworkFinishedCallback) {
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")
        let nsData = NSData(contentsOfFile: path!)!
        let statusesJson = try! NSJSONSerialization.JSONObjectWithData(nsData, options: NSJSONReadingOptions(rawValue: 0))
        finish(result: statusesJson as? [String: AnyObject], error: nil)
    }
    
    func loadStatus(since_id: Int, max_id: Int,finished: NetworkFinishedCallback) {
//        与绑定相反，如果为空执行里面的代码
        guard var parameters = tokenDict(finished) else {
            return
        }
        
        // 添加参数 since_id和max_id
        // 判断是否有传since_id,max_id
        if since_id > 0 {
            parameters["since_id"] = since_id
        } else if max_id > 0 {
            parameters["max_id"] = max_id - 1
        }
        
        let urlStr = "2/statuses/home_timeline.json"
        requestGET(urlStr, parameters: parameters, finshed: finished)
    }
    
    // MARK: - 封装AFN.GET
    func requestGET(URLString: String, parameters: AnyObject?, finshed: NetworkFinishedCallback) {
        
        GET(URLString, parameters: parameters, success: { (_, result) -> Void in
            finshed(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                finshed(result: nil, error: error)
        }
    }
    // MARK: - 封装AFN.POST
    func requestPOST(URLString: String, parameters: AnyObject?, finshed: NetworkFinishedCallback) {
        POST(URLString, parameters: parameters, success: { (_, result) -> Void in
            finshed(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
            finshed(result: nil, error: error)
        }
    }
}




